package com.example.demo.listnode;

import com.example.demo.entity.ListNode;
import org.junit.Test;

import java.util.Optional;

public class ListNodeSum {

    // https://leetcode-cn.com/problems/add-two-numbers/
    public static ListNode<Integer> merge(ListNode<Integer> node1, ListNode<Integer> node2) {
        int carry = 0;
        ListNode<Integer> head = null, tail = null;

        while (node1 != null || node2 != null) {
            int l1 = Optional.ofNullable(node1).map(ListNode::getValue).orElse(0);
            int l2 = Optional.ofNullable(node2).map(ListNode::getValue).orElse(0);

            int sum = l1 + l2 + carry;
            carry = sum / 10;

            if (head == null) {
                tail = head = new ListNode<>(sum % 10);
            } else {
                tail.setNext(new ListNode<>(sum % 10));
                tail = tail.getNext();
            }

            if (node1 != null) {
                node1 = node1.getNext();
            }

            if (node2 != null) {
                node2 = node2.getNext();
            }
        }

        if (carry > 0) {
            tail.setNext(new ListNode<>(carry));
        }

        return head;
    }
}
